<?php
namespace app\common\model;

/**
 * 用户模型
 */

class User extends \app\common\model\Base
{


	//----- 基础配置 ------------
	// protected $name = "user";                    //表明 bc_user
	// protected $pk = 'user_id';                       //主键 默认主键为自动识别，如果需要指定，可以设置
	protected $readonly = ['user_id'];      //只读字段  

	protected $autoWriteTimestamp = true;    
  


	// 类型自动转换，会在写入和读取的时候自动进行类型转换处理
	protected $type = array(
		'user_id'  => 'integer',
	);

	// 自动完成
	protected $auto = [];
	protected $insert = array('create_time','update_time');
	protected $update = array('update_time');

	// 修改器
    protected function setIpAttr()
    {
        return request()->ip();
        return request()->ip(0,true); //获取真是ip
    }
  
 		
 	protected function setStatueAttr($value,$data){
 		return $value ? $value : 1 ; 
 	}


	protected function setPasswordAttr($value, $data=null){
		return md5($value);
		// return md5($value.$data['salt']);
	}

	// 获取器
	protected function getStatusTextAttr($value,$data)
    {
        $status = [-1=>'删除',0=>'禁用',1=>'正常',2=>'待审核'];
        return $status[$data['status']];
    }
    protected function getSexTextAttr($value,$data)
    {
        $status = [0=>'保密',1=>'男',2=>'女'];
        return $status[$data['sex']];
    }
    protected function getRoleAttr($value,$data)
    {
		

    	$user_id = $data['user_id'];
    	$roles = $this->getRoles($user_id);
    	$arr = array();
    	foreach($roles as $role){
    		$role_place = model('role')->get($role['id'])->role_place;
    		$arr[] = $role_place;

    	}

        return implode( '<br/>', $arr ) ;
    }
    protected function getRoleArrAttr($value,$data)
    {
    	$user_id = $data['user_id'];
    	$roles = $this->getRoles($user_id);
    	foreach($roles as $k => $role){
    		$role['role_place'] = model('role')->get($role['id'])->role_place;
    		$roles[$k] = $role;
    	}
        return $roles ;
    }



    /**
     * 关联 
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function getRoles( $user_id ){

    	// dump($this->getpk());
    	// dump($this->data);
    	// dump($this->data[$this->getpk()]);
    	$map = array();
    	$map['a.user_id'] = $user_id ;

    	$rs = db('user_role')
    		->alias('a')
    		->field('a.user_id ,b.*')
    		->join('__ROLE__ b','a.role_id = b.id','INNER') //INNER  LEFT RIGHT FULL 
    		->where($map)
    		->select();

    	return $rs;	


    }





	/**
	 * 用户登录模型
	 * @return $user->user_id;    //登录成功 返回 user_id ;
	 * @return return -1; //用户不存在或禁用
	 * @return return -2; //密码错误
	 */
	public function login($username = '', $password = '', $type = 1){
		$map = array();

		if( \think\Validate::is( $username , 'email') ){
			//$type = 2 ; 
		}else{

		}


		// 拼接 登录账号 类型
		switch ($type) {
			case 1:
				$map['loginname'] = $username;
				break;
			case 2:
				$map['email'] = $username;
				break;
			case 3:
				$map['mobile'] = $username;
				break;
			case 4:
				$map['uid'] = $username;
				break;
			case 5:
				$map['uid'] = $username;
				break;
			default:
				return 0; //参数错误
		}

		$user = $this->where( $map )->find();
		// dump( func_get_args());
		// dump($user->toArray());

		if(isset( $user['status'] ) && $user['status'] > 0  ){
			//验证密码
			if( $this->setPasswordAttr( $password , $user->toArray() ) == $user->password ){
				$this->autoLogin($user);  //更新用户登录信息
				return $user->user_id;    //登录成功 返回 user_id ;
			}else{
				return -2; //密码错误； 
			}
		}else{
			return -1; //用户不存在或禁用
		}


	}



	/**
	 * 自动登录用户
	 * @param  integer $user 用户信息数组
	 */
	private function autoLogin($user){


		/* 更新登录信息 */
		$data = array(
			'user_id'             => $user['user_id'],
			'login'           => array('exp', '`login`+1'), //登录次数+1
			'last_login_time' => time(),
			//'last_login_ip'   => get_client_ip(1),
			'last_login_ip'   => request()->ip(0,true),
		);
		$this->where(array('user_id'=>$user['user_id']))->update($data); //修改数据库


		$user = $this->where(array('user_id'=>$user['user_id']))->find(); //读取更新后的用户信息

		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'user_id'             => $user['user_id'],
			'username'        => $user['username'],
			'last_login_time' => $user['last_login_time'],
		);

		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth)); //数据签名认证
	}

	public function logout(){
		session('user_auth', null);
		session('user_auth_sign', null);
		//	清除session（当前作用域）
		// session(null);
	}


	//
	public function loginCheck($username = '', $password = '', $type = 1){
		$map = array();
		$map['loginname'] = $username;
		$user = $this->where( $map )->find();


		if(!$user){
			return ['code'=>'1001','msg'=>'用户名不存在'];
		}

		if( $this->setPasswordAttr( $password ) != $user->password){
			return ['code'=>'1002','msg'=>'账户或密码错误'];
		}

		if( isset( $user['status'] ) && $user['status'] <=0 ){
			return ['code'=>'1003','msg'=>'用户不存在或禁用'];
		}

		return $user;

	}


    

    
}